﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Ext.Net;
using Ext.Net.UIS;
using KamLib;


namespace Ext.Net.UIS
{

    public static class TermEditorHelper
    {

        public static IEnumerable<AbstractComponent> NewFieldControls<T>(this TermEditor editor, TermNode node, UisCreateControlArgs e, Action<T> afterCreateComponent = null)
            where T : Ext.Net.Field, new()
        {
            var cmp = new T();

            var fc = cmp as ITermBox;
            if (fc != null)
                fc.TermNode = node;
            else
                node.ApplyToField(cmp);

            var cmp0 = node.Title.yes() && node.Title.Prefix.yes() ? new DisplayField { Text = node.Title.Prefix } : null;
            var cmp1 = node.Title.yes() && node.Title.Postfix.yes() ? new DisplayField { Text = node.Title.Postfix } : null;

            if (!(node.InRow() || node.InUnion()) && (cmp0 != null || cmp1 != null))
            {
                var row = new FieldUnion
                {
                    TermNode = node,
                    ViewState = e.BaseViewState,
                };
                node.HidingTitle = true;

                if (cmp0 != null) row.Items.Add(cmp0);
                row.Items.Add(cmp);
                if (cmp1 != null) row.Items.Add(cmp1);

                yield return row;
            }
            else
            {
                if (cmp0 != null) yield return cmp0;
                yield return cmp;
                if (cmp1 != null) yield return cmp1;
            }

            if (afterCreateComponent != null)
                afterCreateComponent(cmp);
        }

    }


}
